vue.extend 实现一个通用的 confirm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<template>
<el-dialog
:modal="false"
:visible.sync="visible"
:width="$utils.toRem(320)"
class="confirm-dialog"
>
<div slot="title">{{title || '提示'}}</div>
<div class="confirm-body">{{text}}</div>
<span
class="dialog-footer"
slot="footer"
>
<el-button
@click="confirmAndClose"
class="confirm-btn"
type="primary"
>确认</el-button>
</span>
</el-dialog>
</template>

<script type="text/ecmascript-6">
import Vue from "vue"
const Confirm = {
name: "Confirm",
props: ["visible", "text", "title", "onConfirm"],
methods: {
confirmAndClose() {
this.onConfirm && this.onConfirm()
this.visible = false
}
}
}
export default Confirm
// 单例减少开销
let instanceCache
// 命令式调用
export const confirm = function(text, title, onConfirm = () => {}) {
if (typeof title === "function") {
onConfirm = title
title = undefined
}
const ConfirmCtor = Vue.extend(Confirm)
const getInstance = () => {
if (!instanceCache) {
instanceCache = new ConfirmCtor({
propsData: {
text,
title,
onConfirm
}
})
// 生成dom
instanceCache.$mount()
document.body.appendChild(instanceCache.$el)
} else {
// 更新属性
instanceCache.text = text
instanceCache.title = title
instanceCache.onConfirm = onConfirm
}
return instanceCache
}
const instance = getInstance()
// 确保更新的prop渲染到dom
// 确保动画效果
Vue.nextTick(() => {
instance.visible = true
})
}
</script>

<style lang="scss" scoped>
.confirm-dialog {
/deep/.el-dialog__body {
padding-top: 20px;
padding-bottom: 20px;
}
.confirm-body {
line-height: 20px;
}
.confirm-btn {
width: 100%;
}
}
</style>

代码来自阅读 sl1673495 的项目源码:vue-netease-music